package com.kuiandjie.web;


import java.io.File;
import java.io.IOException;

import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.google.gson.Gson;
import com.kuiandjie.entity.Employee;
import com.kuiandjie.entity.Files;
import com.kuiandjie.entity.Log;
import com.kuiandjie.entity.Project;
import com.kuiandjie.service.FileService;
import com.kuiandjie.service.LogService;
import com.kuiandjie.util.DateUtil;
import com.kuiandjie.util.UUUtil;




public class UploadServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		if("POST".equals(request.getMethod())){
			HttpSession session = request.getSession();
			
			Employee emp = (Employee) session.getAttribute("employee");
			String folderid = (String) session.getAttribute("folderid");
			//获取服务器内当前工厂的绝对路径
			String path = getServletContext().getRealPath("/");
			//创建upload文件夹和缓存文件夹
			File file = new File(path + "/upload");
			File temp = new File("d:/temp");
			if(!file.exists()) {
				file.mkdir();
			}
			
			if(!temp.exists()) {
				temp.mkdir();
			}
		
			if(ServletFileUpload.isMultipartContent(request)){
				//设置磁盘文件工厂，缓存大小，缓存文件夹
				DiskFileItemFactory dif = new DiskFileItemFactory();
				dif.setSizeThreshold(4096);
				dif.setRepository(temp);
				
				ServletFileUpload servletFileUpload = new ServletFileUpload(dif);
				//单个文件的上传体积限制
				servletFileUpload.setSizeMax(1024*1024*300);
				
				
				try {
					List<FileItem> list = servletFileUpload.parseRequest(request);
					if(list.size()==0 || list == null){
						response.sendRedirect("filelist.jspx?fid=" + folderid);
						return;
					}else{
						
					//把form提交过来的数据进行处理
					for(FileItem item : list){
						if(item.isFormField()){
							//接收不是文件类型的数据
						}else{
							if(item.getSize() > 1024*1024*100){
								
								response.sendRedirect("upload.jspx");
								
								return;
							}
							//判断是不是没有选择文件直接点击上传
							if(item.getName() == ""){
								response.sendRedirect("upload.jspx" );
								return;
							}
							//截取文件的后缀str
							String str = "";
							if(item.getName().indexOf(".") > 0){
								 str = item.getName().substring(item.getName().lastIndexOf("."));
								 
							}else {
								 str = "";
							}
							
							//给文件重命名，防止在upload文件夹里面的重名
							String randomName = UUUtil.getUUID() + str;
							
							//上传到upload
							item.write(new File(file,randomName));
							
						//在数据库中插入一条数据记录上传的文件信息
							String name = item.getName();
							long filesize = item.getSize();
							FileService fs = new FileService();
							Files f = new Files();
							f.setCreateTime(DateUtil.getNow());
							f.setEmployeeId(emp.getId());
							f.setFileName(randomName);
							f.setFileSize(filesize);
							f.setFileTypeId(Integer.parseInt(folderid));
							f.setName(name);
							f.setType(str.toLowerCase());
							fs.addFile(f);
							Project curp = (Project) session.getAttribute("curp");
							Log log = new Log();
							log.setDesc("上传了新文件<a href='filelist.jspx?fid=" + folderid + "'>" + name + "</a>");
							log.setEmployeeId(emp.getId());
							log.setProjectId(curp.getId());
							log.setTime(DateUtil.getNow());
							log.setName(emp.getName());
							log.setPic(emp.getPic());
							
							LogService ls = new LogService();
							ls.inserLog(log);
							
							request.setAttribute("msg", new Gson().toJson(log));
							request.getRequestDispatcher("msgflow.jspx").include(request, response);
							//跳转到文件列表页面
							response.sendRedirect("filelist.jspx?fid="+folderid);
						}
					}
						
					}	
				
				} catch (Exception e) {
					
					e.printStackTrace();
				}
			}
		
		}else{
			//是get请求的直接跳转到上传页面
			
			request.getRequestDispatcher("WEB-INF/views/upload.jsp").forward(request, response);
		}


		}
	
}
	

